# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """

        def ergodic(node):
            if not node.left:
                if not node.right:
                    return True, [node.val, node.val]
                else:
                    r_result, r_list = ergodic(node.right)
                    if r_result and node.val < r_list[0]:
                        return True, [node.val, r_list[1]]
                    else:
                        return False, []
            else:
                if not node.right:
                    l_result, l_list = ergodic(node.left)
                    if l_result and node.val > l_list[1]:
                        return True, [l_list[0], node.val]
                    else:
                        return False, []
                else:
                    l_result, l_list = ergodic(node.left)
                    r_result, r_list = ergodic(node.right)
                    if l_result and r_result and l_list[1] < node.val < r_list[0]:
                        return True, [l_list[0], r_list[1]]
                    else:
                        return False, []

        return ergodic(root)[0]








